package edu.pku.sei.sct.primitives;

import java.util.ArrayList;

import edu.pku.sei.ocl.evaluation.Context;
import edu.pku.sei.ocl.visitor.AbstractOCLVisitor;
import edu.pku.sei.sct.evaluation.RuleContext;
import edu.pku.sei.sct.evaluation.SCTEnvironment;

public class Schedule extends AbstractPrimitive {
	static final public String ID = "Schedule";
	
	class ScheduleTask {
		public String name;
		public Object[] params;
	}
	
	private ArrayList<ScheduleTask> tasks = new ArrayList<ScheduleTask>();

	public Schedule(SCTEnvironment e) {
		super(e);
		// TODO Auto-generated constructor stub
	}
	
	
	public Object execute(AbstractOCLVisitor visitor, Context currentContext, Object... argv) {
		if(argv==null || argv.length==0){
			while(tasks.size()!=0) {
				ArrayList<ScheduleTask> temp = (ArrayList<ScheduleTask>) tasks.clone();
				tasks.clear();
				for(ScheduleTask t : temp) {
					Object retvalue = this.sctEnvironment.invokeHelper(t.name, visitor, t.params);
					if(retvalue instanceof Boolean){
						if((Boolean)retvalue==false)
							return false;
					}
				}
			}
			return true;
		} else {
			return execute(argv);
		}
	}

	
	/**
	 * argv[0] = Helper Name
	 * argv[1..*] = params
	 * argv = null => execute the schedule
	 */
	@Override
	public Object execute(Object... argv) {
		String helperName = (String) argv[0];
		Object[] params = new Object[argv.length-1];
		
		for(int i = 1; i<argv.length; i++) {
			params[i-1] = argv[i];
		}
		
		ScheduleTask task = new ScheduleTask();
		task.name = helperName;
		task.params = params;
		
		tasks.add(task);
		return true;
	}

	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return ID;
	}

}
